#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 2345 

int useage();

struct node
{
    char group[256];
    char passwd[64];
};

struct nodeinfo
{
    char group[256];
    char passwd[64];
    char nodeip[64];
    int  nodeport;
};


struct nodeinfo  nodelist[100];
struct node      node1;

int main(int argc, char *argv[])
{

    int sockfd,len;
    struct sockaddr_in s_addr,r_addr;
    int addr_len = sizeof(struct sockaddr_in);
    int node_index=0;
    char buffer[256];

    if((sockfd = socket(AF_INET,SOCK_DGRAM,0))<0 )
    {
        perror("socket");
        exit(1);
    }
   
    bzero(&s_addr,sizeof(s_addr));
    bzero(&r_addr,sizeof(r_addr));
    s_addr.sin_family = AF_INET;
    s_addr.sin_port = htons(PORT);
    s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    
    if(bind(sockfd,&s_addr,sizeof(s_addr))<0 ) 
    {
        perror("connect");
        exit(1);
    }

//    while(1)
//    {
//       bzero(buffer,sizeof(buffer));
//       len = recvfrom(sockfd,buffer,sizeof(buffer),0,&r_addr,&addr_len);
//       sendto(sockfd,buffer,len,0,&r_addr,addr_len);
//       printf("receive from %s  %d\n",inet_ntoa(r_addr.sin_addr),ntohs(r_addr.sin_port)); 
//    }

    printf("ResourceIP	ResourcePort		Group		Password\n");
    while(1)
    {
       bzero(&node1,sizeof(struct node));
       bzero(&nodelist[node_index],sizeof(struct nodeinfo ));
       len = recvfrom(sockfd,&node1,sizeof(struct node),0,&r_addr,&addr_len);
       strcpy(&nodelist[node_index].nodeip,inet_ntoa(r_addr.sin_addr));
       nodelist[node_index].nodeport = ntohs(r_addr.sin_port);
       strcpy(&nodelist[node_index].group,node1.group);
       strcpy(&nodelist[node_index].passwd,node1.passwd);
       printf("%s\t%d\t\t\t%s\t\t%s\n",nodelist[node_index].nodeip,nodelist[node_index].nodeport,nodelist[node_index].group,nodelist[node_index].passwd);

       int i=0;
       while(i<node_index)
       {
        //   if (strcmp(&nodelist[i].group,node1.group) == 0)
           {
               sendto(sockfd,nodelist[i].nodeip,strlen(nodelist[i].nodeip),0,&r_addr,addr_len);
               printf("i = %d send to %s\n",i, &nodelist[i].nodeip);
           }
           i++;
       }

       sendto(sockfd,"end",strlen("end"),0,&r_addr,addr_len);
 
       node_index++;
      
    }
     

    return 0;
}

int useage()
{
     printf("1. list all numeber\n");
     printf("2. pass a file a number\n");
     printf("\n");
}
